﻿#include <cmath>
#include <QDebug>
#include <QFontMetrics>
#include "element.h"


DrawRCircle::DrawRCircle(void)
{
    m_centre = QPoint(0, 0);
    m_drawType = RCIRCLE;
    m_radius = 0;
    m_state = Element::DS_IDLE;
}

int	DrawRCircle::mouseMove(QPoint point)
{
    if( m_state == Element::DS_STATE1 )
    {
        QPoint pt = point - m_centre;
        setTempRadius(hypot(pt.x(), pt.y()));
        return 1;
    }
    return 0;
}

int	DrawRCircle::mouseLButtonPress(QPoint point)
{
    if( m_state == Element::DS_IDLE )
    {
        setCentre(point);
        return 1;
    }
    return 0;
}

inline void DrawRCircle::setCentre(QPoint point)
{
    m_centre = point;
    m_state = Element::DS_STATE1;
}

void DrawRCircle::setRadius(double r)
{
    m_radius = r;
    m_textBox.moveTo(m_centre);
    updateText();
    m_state = Element::DS_FINISH;
}

void DrawRCircle::build(QPoint center, double radius)
{
    setCentre(center);
    setRadius(radius);
}

inline void DrawRCircle::setTempRadius(double r)
{
    m_radius = r;
}

int DrawRCircle::mouseLButtonRelease(QPoint point)
{
    if( m_state == Element::DS_STATE1 )
    {
        QPoint pt = point - m_centre;
        setRadius(hypot(pt.x(), pt.y()));
        if( m_radius < 6 )
        {
            m_state = Element::DS_ERROR;
        }
        return 1;
    }
    return 0;
}

void DrawRCircle::draw( QPainter &painter )
{
    if( m_state != Element::DS_IDLE )
    {
        painter.save();
        painter.setPen(m_linePen);
        int x, y, width, height;

        painter.drawLine(m_centre.x() - 5, m_centre.y(), m_centre.x() + 5, m_centre.y());
        painter.drawLine(m_centre.x(), m_centre.y() - 5, m_centre.x(), m_centre.y() + 5);

        x = m_centre.x() - m_radius;
        y = m_centre.y() - m_radius;
        width = 2 * m_radius;
        height = 2 * m_radius;
        painter.drawArc ( x, y, width, height, 0, 16 * 360 );
        if( m_state == Element::DS_FINISH )
        {
            painter.setFont(m_textFont);
            painter.drawText(m_textBox, m_text);
        }
        painter.restore();
    }
}

void DrawRCircle::updateText(void)
{
   // m_text = QString("D = %1 um").arg(2 * m_radius * m_scale, 2, 'f', 2);
    if(m_radius * m_scale >= 500.0)
    {
        m_text = QString::fromUtf8("D = %1 mm").arg(2 * m_radius * m_scale / 1000.0, 2, 'f', 2);
    }
    else
    {
        m_text = QString::fromUtf8("D = %1 μm").arg(2 * m_radius * m_scale, 2, 'f', 2);
    }
    QFontMetrics fm(m_textFont);
    int textWidth = fm.width(m_text);
    int textHeight = fm.height();
    m_textBox.setWidth(textWidth);
    m_textBox.setHeight(textHeight);
}

void DrawRCircle::computeBox()
{

}

